package com.zhuoyue;

import com.zhuoyue.exception.NotInitConnectionException;

/**
 * 核心client类
 *
 *
 * 一个轮回的对视，我曾是你，你终会是我
 *
 *
 * @author Created by mr.liang
 */
public class Client {

    /** 配置管理 */
    private ClientConfig clientConfig;

    /** 回调实例 */
    private Callback callback;

    /** 连接管理 */
    private ConnectionManagement connectionManagement;

    /** 读取管理 */
    private ReadThreadManagement readThreadManagement;

    /** 写入管理 */
    private WriterManagement writerManagement;

    /** 心跳管理 */
    private HeartbeatManagement heartbeatManagement;


    /**
     * 推荐构造
     * @param serverIp 服务ip
     * @param serverPort 服务端口
     */
    public Client(String serverIp,int serverPort) {
        this(new ClientConfig(serverIp,serverPort));
    }

    public Client(ClientConfig clientConfig) {
        this.clientConfig = clientConfig;
        connectionManagement = new ConnectionManagement(clientConfig);
        readThreadManagement = new ReadThreadManagement(clientConfig,this,connectionManagement);
        writerManagement = new WriterManagement(connectionManagement,clientConfig);
        heartbeatManagement = new HeartbeatManagement(clientConfig,connectionManagement,writerManagement);
    }


    public void registerCallback(Callback callback) {
        this.callback = callback;
    }

    /**
     * 使用类似Thread
     * 1.继承类覆盖这个方法
     * 2.在构造器传入callback实例
     */
    protected void callback(String data){
        if(callback==null){
            throw new RuntimeException("not fount callback");
        }
        callback.callback(data);
    }

    /**
     * 连接
     */
    public void connection(){
        if(connectionManagement.connect()){
            readThreadManagement.start();
            heartbeatManagement.start();
        }
    }

    /**
     * 发送json数据给后台
     */
    public void write(String json){
        if(connectionManagement.isNotInitConnect()){
            throw new NotInitConnectionException();
        }
        writerManagement.send(json);
    }

    /**
     * 返回配置
     */
    public ClientConfig getClientConfig() {
        return clientConfig;
    }
}
